package com.gcit.seniorWish.web.common.constant.factory;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gcit.seniorWish.web.common.constant.cache.Cache;
import com.gcit.seniorWish.web.common.constant.cache.CacheKey;
import com.gcit.seniorWish.web.common.constant.enums.ManagerStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.MenuStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.SystemConfigurateEnum;
import com.gcit.seniorWish.web.core.log.LogObjectHolder;
import com.gcit.seniorWish.core.support.StrKit;
import com.gcit.seniorWish.core.util.Convert;
import com.gcit.seniorWish.core.util.SpringContextHolder;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.common.persistence.dao.*;
import com.gcit.seniorWish.web.common.persistence.model.*;
import com.gcit.seniorWish.web.modular.system.dao.DeptDao;
import com.gcit.seniorWish.web.modular.system.dao.RoleDao;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 常量的生产工厂
 *
 * @author fengshuonan
 * @date 2017年2月13日 下午10:55:21
 */
@Component
@DependsOn("springContextHolder")
public class ConstantFactory implements IConstantFactory {

	private RoleMapper roleMapper = SpringContextHolder.getBean(RoleMapper.class);
	private RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private DeptMapper deptMapper = SpringContextHolder.getBean(DeptMapper.class);
	private DeptDao deptDao = SpringContextHolder.getBean(DeptDao.class);
	private DictMapper dictMapper = SpringContextHolder.getBean(DictMapper.class);
	private UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
	private MenuMapper menuMapper = SpringContextHolder.getBean(MenuMapper.class);
	private NoticeMapper noticeMapper = SpringContextHolder.getBean(NoticeMapper.class);
	private SeniorSchoolMapper schoolMapper = SpringContextHolder.getBean(SeniorSchoolMapper.class);
	private SeniorSchoolClassMapper classMapper = SpringContextHolder.getBean(SeniorSchoolClassMapper.class);
	private EnrollSchoolMapper enrollSchoolMapper = SpringContextHolder.getBean(EnrollSchoolMapper.class);
	private EnrollSchoolBatchMajorMapper enrollMajorMapper = SpringContextHolder.getBean(EnrollSchoolBatchMajorMapper.class);
	private SystemConfigurateMapper systemConfigMapper = SpringContextHolder.getBean(SystemConfigurateMapper.class);
	private SeniorExamineeMapper examineeMapper = SpringContextHolder.getBean(SeniorExamineeMapper.class);

	public static IConstantFactory me() {
		return SpringContextHolder.getBean("constantFactory");
	}

	/**
	 * 根据用户id获取用户名称
	 *
	 * @author stylefeng
	 * @Date 2017/5/9 23:41
	 */
	@Override
	public String getUserNameById(String userId) {
		User user = userMapper.selectById(userId);
		if (user != null) {
			return user.getName();
		} else {
			return "--";
		}
	}

	/**
	 * 根据用户id获取用户账号
	 *
	 * @author stylefeng
	 * @date 2017年5月16日21:55:371
	 */
	@Override
	public String getUserAccountById(String userId) {
		User user = userMapper.selectById(userId);
		if (user != null) {
			return user.getAccount();
		} else {
			return "--";
		}
	}

	/**
	 * 通过角色ids获取角色名称
	 */
	@Override
	public String getRoleName(String userId) {
		List<String> roleIdList = roleDao.listRoleIdByUserId(userId);
		StringBuilder sb = new StringBuilder();
		for (String roleId : roleIdList) {
			if (StrUtil.isNotBlank(roleId)) {
				sb.append(this.getSingleRoleName(roleId)).append(",");
			}
		}
		return StrKit.removeSuffix(sb.toString(), ",");
	}

	/**
	 * 通过角色id获取角色名称
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId")
	public String getSingleRoleName(String roleId) {
		if (StrUtil.isBlank(roleId)) {
			return "--";
		}
		Role roleObj = roleMapper.selectById(roleId);
		if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
			return roleObj.getName();
		}
		return "";
	}

	/**
	 * 通过角色id获取角色英文名称
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_TIP + "'+#roleId")
	public String getSingleRoleRemark(String roleId) {
		if (StrUtil.isBlank(roleId)) {
			return "--";
		}
		Role roleObj = roleMapper.selectById(roleId);
		if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
			return roleObj.getRemark();
		}
		return "";
	}

	/**
	 * 获取部门名称
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DEPT_NAME + "'+#deptId")
	public String getDeptName(String deptId) {
		Dept dept = deptMapper.selectById(deptId);
		if (ToolUtil.isNotEmpty(dept) && ToolUtil.isNotEmpty(dept.getName())) {
			return dept.getName();
		}
		return "";
	}

	/**
	 * 获取菜单的名称们(多个)
	 */
	@Override
	public String getMenuNames(String menuIds) {
		Integer[] menus = Convert.toIntArray(menuIds);
		StringBuilder sb = new StringBuilder();
		for (int menu : menus) {
			Menu menuObj = menuMapper.selectById(menu);
			if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
				sb.append(menuObj.getName()).append(",");
			}
		}
		return StrKit.removeSuffix(sb.toString(), ",");
	}

	/**
	 * 获取菜单名称
	 */
	@Override
	public String getMenuName(String menuId) {
		if (ToolUtil.isEmpty(menuId)) {
			return "";
		} else {
			Menu menu = menuMapper.selectById(menuId);
			if (menu == null) {
				return "";
			} else {
				return menu.getName();
			}
		}
	}

	/**
	 * 获取菜单名称通过id
	 */
	@Override
	public String getMenuNameById(String id) {
		if (ToolUtil.isEmpty(id)) {
			return "";
		} else {
			Menu param = new Menu();
			param.setId(id);
			Menu menu = menuMapper.selectOne(param);
			if (menu == null) {
				return "";
			} else {
				return menu.getName();
			}
		}
	}

	/**
	 * 获取通知标题
	 */
	@Override
	public String getNoticeTitle(String dictId) {
		if (ToolUtil.isEmpty(dictId)) {
			return "";
		} else {
			Notice notice = noticeMapper.selectById(dictId);
			if (notice == null) {
				return "";
			} else {
				return notice.getTitle();
			}
		}
	}

	/**
	 * 获取字典名称
	 */
	@Override
	public String getDictName(String dictId) {
		if (ToolUtil.isEmpty(dictId)) {
			return "";
		} else {
			Dict dict = dictMapper.selectById(dictId);
			if (dict == null) {
				return "";
			} else {
				return dict.getName();
			}
		}
	}

	/**
	 * 根据字典名称和字典中的值获取对应的名称
	 */
	@Override
	public String getDictsByName(String name, Integer val) {
		Dict temp = new Dict();
		temp.setName(name);
		Dict dict = dictMapper.selectOne(temp);
		if (dict == null) {
			return "";
		} else {
			Wrapper<Dict> wrapper = new EntityWrapper<>();
			wrapper = wrapper.eq("pid", dict.getId());
			List<Dict> dicts = dictMapper.selectList(wrapper);
			for (Dict item : dicts) {
				if (item.getNum() != null && item.getNum().equals(val)) {
					return item.getName();
				}
			}
			return "";
		}
	}

	/**
	 * 根据父级字典的名称查询字典列表
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DICT_LIST + "'+#pcode")
	public List<Dict> listDictsByPCode(String pcode) {
		return dictMapper.selectList(Condition.create().eq("pcode", pcode).orderBy("num"));
	}

	/**
	 * 根据父级和自己的字典编码获取字典名称
	 *
	 * @param pcode
	 * @param code
	 * @return
	 */
	@Override
	public Dict getDictByCode(String pcode, String code) {
		Dict temp = new Dict();
		temp.setPcode(pcode);
		temp.setCode(code);
		Dict dict = dictMapper.selectOne(temp);
		if (dict == null) {
			return null;
		} else {
			return dict;
		}
	}

	/**
	 * 根据父级字典编码与自己的字典值获取字典
	 *
	 * @param pcode
	 * @param value
	 * @return
	 */
	@Override
	public Dict getDictByCodeAndValue(String pcode, Object value) {
		Dict temp = new Dict();
		temp.setPcode(pcode);
		temp.setValue(String.valueOf(value));
		Dict dict = dictMapper.selectOne(temp);
		if (dict == null) {
			return null;
		} else {
			return dict;
		}
	}

	/**
	 * 查询字典
	 */
	@Override
	public List<Dict> findInDict(String id) {
		if (ToolUtil.isEmpty(id)) {
			return null;
		} else {
			EntityWrapper<Dict> wrapper = new EntityWrapper<>();
			List<Dict> dicts = dictMapper.selectList(wrapper.eq("pid", id));
			if (dicts == null || dicts.size() == 0) {
				return null;
			} else {
				return dicts;
			}
		}
	}

	/**
	 * 获取性别名称
	 */
	@Override
	public String getSexName(Integer sex) {
		return getDictsByName("性别", sex);
	}

	/**
	 * 获取用户登录状态
	 */
	@Override
	public String getStatusName(Integer status) {
		return ManagerStatusEnum.valueOf(status);
	}

	/**
	 * 获取菜单状态
	 */
	@Override
	public String getMenuStatusName(Integer status) {
		return MenuStatusEnum.valueOf(status);
	}

	/**
	 * 获取被缓存的对象(用户删除业务)
	 */
	@Override
	public String getCacheObject(String para) {
		return LogObjectHolder.me().get().toString();
	}

	/**
	 * 获取子部门id
	 */
	@Override
	public List<String> getSubdeptId(String deptId, boolean includeSelf) {
		List deptIds = this.getSubdeptId(deptId);
		if (includeSelf) {
			deptIds.add(deptId);
		}
		return deptIds;
	}

	/**
	 * 获取子部门id
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SUB_DEPT_ID_LIST + "'+#deptId")
	public List<String> getSubdeptId(String deptId) {
		return this.deptDao.getSubdeptId(deptId);
	}

	/**
	 * 获取所有父部门id
	 */
	@Override
	public List<String> getParentdeptIds(String deptId) {
		Dept dept = deptMapper.selectById(deptId);
		if (dept != null) {
			return null;
		}
		String pids = dept.getPids();
		String[] split = pids.split(",");
		ArrayList<String> parentdeptIds = new ArrayList<>();
		for (String s : split) {
			parentdeptIds.add(String.valueOf(StrKit.removeSuffix(StrKit.removePrefix(s, "["), "]")));
		}
		return parentdeptIds;
	}

	/**
	 * 获取父级区域的名称
	 */
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.PDEPT_NAME + "'+#deptId")
	public String getParentDeptName(String deptId) {
		Dept dept = deptMapper.selectById(deptId);
		String pid = dept.getPid();
		if (pid != null) {
			return deptMapper.selectById(pid).getName();
		} else {
			return null;
		}
	}


	/**
	 * 根据id获取学校名称
	 */
	@Override
	@Cacheable(value = Cache.BUSS, key = "'" + CacheKey.SENIOR_SCHOOL + "'+#schoolId")
	public SeniorSchool getSeniorSchoolById(String schoolId) {
		SeniorSchool school = schoolMapper.selectById(schoolId);
		if (school != null) {
			return school;
		} else {
			return new SeniorSchool();
		}
	}

	/**
	 * 根据id获取班级
	 */
	@Override
	@Cacheable(value = Cache.BUSS, key = "'" + CacheKey.SENIOR_CLASS + "'+#classId")
	public SeniorSchoolClass getSeniorSchoolClassById(String classId) {
		SeniorSchoolClass clazz = classMapper.selectById(classId);
		if (clazz != null) {
			return clazz;
		} else {
			return new SeniorSchoolClass();
		}
	}

	/**
	 * 根据报考学校id查询学校
	 *@param enrollSchoolId 报考学校id
	 * @author gaozhichang
	 * @date 2018年03月24日 15:35
	 */
	@Override
	@Cacheable(value = Cache.BUSS, key = "'" + CacheKey.ENROLL_SCHOOL + "'+#enrollSchoolId")
	public EnrollSchool getEnrollSchoolById(String enrollSchoolId){
		EnrollSchool enrolleSchool = enrollSchoolMapper.selectById(enrollSchoolId);
		if(enrolleSchool!=null){
			return enrolleSchool;
		}else{
			return new EnrollSchool();
		}
	}

	/**
	 * 根据报考学校id查询专业
	 * @param enrollMajorId 报考专业id
	 * @author gaozhichang
	 * @date 2018年03月24日 15:35
	 */
	@Override
	@Cacheable(value = Cache.BUSS, key = "'" + CacheKey.ENROLL_MAJOR + "'+#enrollMajorId")
	public EnrollSchoolBatchMajor  getEnrollMajorById(String enrollMajorId){
		EnrollSchoolBatchMajor enrollMajor = enrollMajorMapper.selectById(enrollMajorId);
		if(enrollMajor != null){
			return enrollMajor;
		}else{
			return new EnrollSchoolBatchMajor();
		}
	}


	/**
	* 查询系统配置
	* @param configurateKey 系统配置的键
	* @author gaozhichang
	* @date 2018-04-03 上午 10:36
	*/
	@Override
	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SYS_CONFIG + "'+#configurateKey")
	public SystemConfigurate getSystemConfigurateByKey(String configurateKey){
		List<SystemConfigurate> list = systemConfigMapper.selectList(Condition.create().eq("configurate_key", SystemConfigurateEnum.SENIOR_WISH_END_DATE.getMessage()));
		if(list.size()>=0){
			return list.get(0);
		}else{
			return null;
		}
	}

}
